from django.db.models import Avg, Count
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.My_Forms import EmpForm


# Create your views here.

def add_book(request):
    # book = models.Book(title="菜鸟教程",price=300,publish="菜鸟出版社",pub_date="2008-8-8")
    # book.save()
    # return HttpResponse("<p>数据添加成功！</p>")
    # books = models.Book.objects.create(title="如来神掌",price=200,publish="功夫出版社",pub_date="2010-10-10")
    # print(books, type(books))
    # return HttpResponse("<p>数据添加成功！</p>")
    #  获取出版社对象
    # pub_obj = models.Publish.objects.filter(pk=1).first()
    # #  给书籍的出版社属性publish传出版社对象
    # # book = models.Book.objects.create(title="菜鸟教程主键测试", price=300, pub_date="2010-10-20", publish=pub_obj)
    # book = models.Book.objects.create(title="菜鸟教程主键测试", price=300, pub_date="2010-10-20", publish_id=pub_obj.pk)
    #  获取作者对象
    # chong = models.Author.objects.filter(name="令狐冲").first()
    # ying = models.Author.objects.filter(name="任盈盈").first()
    # #  获取书籍对象
    # book = models.Book.objects.filter(title="菜鸟教程").first()
    # #  给书籍对象的 authors 属性用 add 方法传作者对象
    # book.authors.add(chong, ying)
    # return HttpResponse(book)
    # chong = models.Author.objects.filter(name='令狐冲').first()
    # pk = chong.pk
    # book = models.Book.objects.filter(title="冲灵剑法").first()
    # book.authors.add(pk)
    # return HttpResponse(book)
    # pub = models.Publish.objects.filter(name="华山出版社").first()
    # res = pub.book_set.all()
    # for i in res:
    #     print(i.title)
    # aggregate是一个终止子句，使用后会将聚合后的数据转为字典
    res = models.Book.objects.aggregate(a = Avg('price'), c = Count('id'))
    print(res, type(res))
    return HttpResponse("ok")

def find_book(request):
    # book = models.Book.objects.first()
    # books = models.Book.objects.filter(price__in=[200,300])
    books = models.Book.objects.filter(pub_date__day=10)
    for i in books:
        print(i.title)
    return HttpResponse("<p>查找成功！</p>")

@csrf_exempt
def add_emp(request):
    if request.method == "GET":
        form = EmpForm()
        return render(request, "add_emp.html", {"form": form})
    else:
        form = EmpForm(request.POST)
        # 此时form是EmpForm的一个对象实例，也就是一个表单对象
        if form.is_valid():  # 进行数据校验
            # 校验成功
            data = form.cleaned_data  # 校验成功的值，会放在cleaned_data里。
            data.pop('r_salary')

            models.Emps.objects.create(**data)
            return HttpResponse(
                'ok'
            )
        else:
            # 打印错误信息，这一步获取的就是字段的错误信息
            for field, errors in form.errors.items():
                print(field, errors)
            # 获取的是全局错误
            clean_errors = form.errors.get("__all__")
            print("全局错误",clean_errors)
        return render(request, "add_emp.html", {"form": form, "clean_errors": clean_errors})


def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    username = request.POST.get("username")
    password = request.POST.get("pwd")

    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    print(user_obj.username)

    if not user_obj:
        return redirect("/login/")
    else:
        rep = redirect("/index/")
        rep.set_cookie("is_login", True)
        return rep


def index(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')  # 收到浏览器的再次请求,判断浏览器携带的cookie是不是登录成功的时候响应的 cookie
    if not status:
        return redirect('/login/')
    return render(request, "index.html")


def logout(request):
    rep = redirect('/login/')
    rep.delete_cookie("is_login")
    return rep  # 点击注销后执行,删除cookie,不再保存用户状态，并弹到登录页面


def order(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')
    if not status:
        return redirect('/login/')
    return render(request, "order.html")
